import { App } from 'vue'

import { InjectionKey } from 'vue'
import { createStore, Store } from 'vuex'

import { menuStoreType, State } from '#/menuStore/menuStoreType'
import { getAdminInfoApi } from '@/request/login/loginApi'

export const key: InjectionKey<Store<State>> = Symbol()

export const store = createStore<State>({
  state: {
    menus: [],
  },
  getters: {
    getNewMenus(state) {
      const menus = state.menus.sort((a, b) => a.parentId - b.parentId)
      const newMenus: menuStoreType[] = []

      for (let index = 0; index < menus.length; index++) {
        if (menus[index].parentId === 0) {
          const newItem = {
            topMenu: menus[index],
            children: [],
          }
          newMenus.push(newItem)
        } else {
          const itemIndex = newMenus.findIndex(
            (newItem) => newItem.topMenu.id === menus[index].parentId
          )
          newMenus[itemIndex].children.push(menus[index])
        }
      }

      return newMenus
    },
  },
  mutations: {
    updateMenus(state, payload) {
      state.menus = payload
    },
  },
  actions: {
    getAdminInfo({ commit }) {
      return new Promise(async (resolve, reject) => {
        try {
          let info = await getAdminInfoApi()
          if (info.code === 200) {
            console.log(info)
            commit('updateMenus', info.data.menus)
            resolve(info.data)
          }
        } catch (error) {
          reject(error)
        }
      })
    },
  },
  modules: {},
})

export const initStore = (app: App<Element>) => {
  app.use(store, key)
}
